package com.atguigu.orderservice.service.impl;

import com.atguigu.commonutils.vo.CommonCourseInfoVo;
import com.atguigu.commonutils.vo.CommonMember;
import com.atguigu.orderservice.client.EduClient;
import com.atguigu.orderservice.client.UcenterClient;
import com.atguigu.orderservice.entity.TOrder;
import com.atguigu.orderservice.mapper.TOrderMapper;
import com.atguigu.orderservice.service.TOrderService;
import com.atguigu.orderservice.util.OrderNoUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author xuan
 * @since 2020-04-24
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Autowired
    EduClient eduClient;
    @Autowired
    UcenterClient ucenterClient;

    @Override
    public String saveOrder(String courseId, String memberIdByJwtToken) {
        CommonCourseInfoVo courseInfoVo = eduClient.getCourseInfoDto(courseId);
        CommonMember commonMember = ucenterClient.getCommonMember(memberIdByJwtToken);
        TOrder order = new TOrder();
        order.setOrderNo(OrderNoUtil.getOrderNo());
        order.setCourseId(courseId);
        order.setCourseTitle(courseInfoVo.getTitle());
        order.setCourseCover(courseInfoVo.getCover());
        order.setTeacherName("test");
        order.setTotalFee(courseInfoVo.getPrice());
        order.setMemberId(memberIdByJwtToken);
        order.setMobile(commonMember.getMobile());
        order.setNickname(commonMember.getNickname());
        order.setStatus(0);
        order.setPayType(1);
        //如有该用户该课程未支付订单,删除未支付订单
        QueryWrapper<TOrder> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("member_id",memberIdByJwtToken)
                .eq("course_id",courseId)
                .ne("status",1);
        baseMapper.delete(orderWrapper);
        int insert = baseMapper.insert(order);
        if(insert > 0){
            return order.getOrderNo();
        }
        return null;
    }
}
